package com.lcg.exchange.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MyAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private MyUserDetailsService myUserDetailsService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();
        log.info("VAuthenticationProvider authenticate login user [username={}, password={}]", username, password);
        UserDetails userDetails = myUserDetailsService.loadUserByUsername(username);
        //log.info("VAuthenticationProvider authenticate vUserDetails [vUserDetails={}]", userDetails.toString());
        if(userDetails == null){
            throw new BadCredentialsException("该账号不存在，请重新输入！");
        }
        if (!password.equals(userDetails.getPassword())) {
            log.info("VAuthenticationProvider authenticate BadCredentialsException [inputPassword={}, DBPassword={}]", password, userDetails.getPassword());
            throw new BadCredentialsException("密码错误，请重新输入！");
        }
        //认证校验通过后，封装UsernamePasswordAuthenticationToken返回
        return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());

    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
